﻿using System;
using System.Collections;
using GpgApi;

namespace WgpgCore
{
    public sealed class KeyNodeSort : IComparer
    {
        public readonly Boolean GroupByKey;

        public KeyNodeSort(Boolean groupByKey)
        {
            GroupByKey = groupByKey;
        }

        public Int32 Compare(Object x, Object y)
        {
            KeyNode key1 = x as KeyNode;
            KeyNode key2 = y as KeyNode;

            if (Object.ReferenceEquals(key1, key2))
                return 0;

            if (key1 == null)
                return -1;

            if (key2 == null)
                return 1;

            if (GroupByKey)
            {
                if (key1.Type == KeyType.Pair && key2.Type == KeyType.Public)
                    return -1;

                if (key1.Type == KeyType.Public && key2.Type == KeyType.Pair)
                    return 1;
            }

            String name1 = key1.UserInfos[0].Name;
            String name2 = key2.UserInfos[0].Name;

            return String.Compare(name1, name2, StringComparison.CurrentCultureIgnoreCase);
        }
    }
}
